package ink.lovejinhu.leetcodeMatch;

import ink.lovejinhu.common.TreeNode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

public class Solution_5810 {

    public TreeNode canMerge(List<TreeNode> trees) {

        HashSet<Integer> result = new HashSet<Integer>();
        for (TreeNode var : trees
        ) {
            print(var, result);
        }
        Iterator<Integer> iterator = result.iterator();
        ArrayList<Integer> integers = new ArrayList<Integer>();
        while (iterator.hasNext()) {
            integers.add(iterator.next());
        }
        int[] ints = new int[integers.size()];
        for (int i = 0; i < integers.size(); i++) {
            ints[i] = integers.get(i);
        }
        Arrays.sort(ints);
        TreeNode treeNode = sortedArrayToBST(ints);
        return treeNode;
    }

    public TreeNode sortedArrayToBST(int[] nums) {
        return this.buildTree(nums, 0, nums.length - 1);
    }

    public TreeNode buildTree(int nums[], int left, int right) {
        if (right < left) {
            return null;
        }
        int mid = (right + left) >> 1;   //有溢出风险
        TreeNode root = new TreeNode(nums[mid]);
        root.left = buildTree(nums, left, mid - 1);
        root.right = buildTree(nums, mid + 1, right);
        return root;
    }

    public void print(TreeNode temp, HashSet<Integer> param) {
        if (temp == null) {
            return;
        }
        if (param.contains(temp.val)) {

        } else {
            param.add(temp.val);
        }
        print(temp.left, param);
        print(temp.right, param);
    }
}
